package com.clothing;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.clothing.entity.User;
import com.clothing.service.UserService;
import com.clothing.utils.Utils;

public class AuthenticationRealm extends AuthorizingRealm
{
    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals)
    {
        Principal principal = (Principal) principals.fromRealm(getName())
                .iterator().next();
        if (principal != null)
        {
            List<String> authorities = new ArrayList<String>();
            if (authorities != null)
            {
                SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
                authorizationInfo.addStringPermissions(authorities);
                return authorizationInfo;
            }
        }

        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException
    {
        UsernamePasswordToken passwordToken = (UsernamePasswordToken) token;
        String username = passwordToken.getUsername();
        String password = new String(passwordToken.getPassword());

        if (!Utils.isMobile(username) || Utils.isEmpty(password))
        {
            throw new AccountException();
        }

        User user = userService.findByMobile(username);

        if (null == user)
        {
            throw new AccountException();
        }

//        if (!user.getEnabled())
//        {
//            throw new DisabledAccountException();
//        }

//        if (!user.getPassword().equals(DigestUtils.sha256Hex(password)))
//        {
//            throw new IncorrectCredentialsException();
//        }

        return new SimpleAuthenticationInfo(new Principal(user.getId(),
                password), password, getName());
    }
}
